package com.zretc.auth.contoller;

import com.common.core.domain.CodeMessage;
import com.common.core.utils.AuthUtil;
import com.common.core.utils.JwtUtils;
import com.common.core.utils.SecurityUtils;
import com.common.core.utils.StringUtils;
import com.zretc.auth.service.TokenService;
import com.zretc.pojo.LoginUserPojo;
import com.zretc.auth.service.SysLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class TokenController {
    @Autowired
    private SysLoginService routeloginservice;
    @Autowired
    private TokenService tokenService;
    @PostMapping("login")
    public CodeMessage login(@RequestBody LoginUserPojo user) {


       LoginUserPojo user1 = routeloginservice.login(user.getUsername(), user.getPassword());
       return CodeMessage.success(tokenService.creatToken(user1));
    }
    @DeleteMapping("logout")
    public CodeMessage<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            tokenService.logout(username);
        }
        return R.ok();
    }
}
